package com.zyy.game.tianlong.callback;

import com.zyy.game.tianlong.entity.GamePlayer;
import com.zyy.game.tianlong.network.GameManage;
import com.zyy.game.tianlong.network.GameContext;
import com.zyy.game.tianlong.network.callback.InActiveCallBack;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 断开连接事件
 *
 * @author relufi
 * @date 2019/7/24 0024
 */
@Component
@Slf4j
public class InActiveCallBackImpl implements InActiveCallBack {
    private final GameManage gameManage;

    public InActiveCallBackImpl(GameManage gameManage) {
        this.gameManage = gameManage;
    }

    @Override
    public void channelInactive(GameContext ctx) {
        Channel channel = ctx.getContext().channel();
        AttributeKey<GamePlayer> key = AttributeKey.valueOf(GameManage.ID_KEY);
        if (channel.hasAttr(key)) {
            Attribute<GamePlayer> attr = channel.attr(key);
            GamePlayer gamePlayer = attr.get();
            if (gamePlayer != null) {
                gameManage.remove(gamePlayer.getPlayerId(), ctx);
                attr.set(null);
            }
        }
        log.debug("断开连接");
    }
}
